package com.youtills.resource;

import com.youtills.core.lang.NumberUtil;
import com.youtills.action.ActionContext;

/**
 * TODO - !!!doc me!!!
 *
 * @author ravi.chiluveru
 * @since 23.0 (7/28/14)
 */
public abstract class EditResourceController<T extends ResourceResponse> implements ResourceController<T> {

    private final ActionContext actionContext;
    private final Resource resource;

    public EditResourceController(ActionContext actionContext) {
        this.actionContext = actionContext;
        this.resource = findResource();
    }

    private Resource findResource(){
       final Long resourceType = NumberUtil.parseLong(this.actionContext.getRequest().getRequestParam(Resource.RESOURCE_TYPE));

       if(resourceType != null) {
           Class resourceTypeClass = getResourceTypeClass(resourceType);
           if(resourceTypeClass != null) {
               final Long resourceId = NumberUtil.parseLong(this.actionContext.getRequest().getRequestParam(Resource.RESOURCE_ID));
               if(resourceId != null) {
                   return ResourceManager.instance.getResource(actionContext, resourceTypeClass, resourceId);
               } else {
                   return ResourceManager.instance.newResource(actionContext, resourceTypeClass);
               }
           }
       }
       return null;
    }

    private Class getResourceTypeClass(long resourceType) {
        //TODO - make it dynamic.
        if(100001 == resourceType) {
            return getClass("com.goodedeeds.domain.resource.Vendor");
        } else if(100002 == resourceType){
            return getClass("com.goodedeeds.domain.resource.School");
        } else if(100003 == resourceType){
            return getClass("com.goodedeeds.domain.resource.Project");
        } else {
            return null;
        }
    }

    private static Class getClass(String name) {
        try {
            return Class.forName(name);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    public T execute(){
        return null;
    }

    public ActionContext getActionContext() {
        return actionContext;
    }

    public Resource getResource() {
        return resource;
    }
}
